package cn.itlaobing.web.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.itlaobing.web.annotation.RequestAnnocation;
import org.apache.taglibs.standard.lang.jstl.StringLiteral;

/** 
 * ClassName: BaseServlet <br/> 
 * Function: 初始化erquest，并且调用所得请求的方法<br/> 
 * date: 2017年10月31日 下午9:48:20 <br/> 
 * 
 * @author 吕正强 
 * @version  
 * @since JDK 1.8 
 */
public class BaseServlet extends HttpServlet{
	//用于存放发过来的请求的，比如增加、删除、修改、查询等
	//其中的键值为拼接的字符串（如：／serlver/delete）
	//其中的value值为对应的annotation的方法
	private Map<String,Method> map=new HashMap<String,Method>();
	@Override
	public void init(ServletConfig config) throws ServletException {
		//获得类
		Class cls=this.getClass();
		//获得基础url(webServlet)
		WebServlet url=(WebServlet)cls.getAnnotation(WebServlet.class);
		//获得方法
		Method[] methods=cls.getDeclaredMethods();
		for (Method method : methods){
			if(method.isAnnotationPresent(RequestAnnocation.class)) {
				RequestAnnocation ra=(RequestAnnocation)method.getAnnotation(RequestAnnocation.class);
				String rastr=ra.value();
				if(!rastr.startsWith("/")) {
					rastr += "/";
				}
				String str=url.value()[0].replace("/*","")+rastr;
				map.put(str,method);
			}
		}
	}
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response){
		//获取当前请求的url
		String url=request.getRequestURI();
		Method method=map.get(url);
		if(method==null) {
			try {
				response.sendError(404);
			} catch (IOException e) {
				e.printStackTrace();
			}
			return;
		}
		try {
			//执行该方法
			method.invoke(this,request,response);
		}catch(InvocationTargetException e) {
			e.printStackTrace();			
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
}
